package com.hitqz.robot.biz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.hitqz.robot.api.business.entity.SysConfigEntity;
import com.hitqz.robot.api.business.vo.SysConfigVo;
import com.hitqz.robot.api.dispatch.protocol.dto.ModifySysInfoDto;
import com.hitqz.robot.biz.service.SysConfigService;
import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author xupkun
 * @date 2024/5/20
 */

@RestController
@AllArgsConstructor
@RequestMapping("/sysConfig")
@Tag(name = "系统配置")
public class SysConfigController {

    private final SysConfigService sysConfigService;

    @GetMapping
    @Operation(summary = "系统配置-无需任何权限")
    public R<SysConfigVo> index() {
        SysConfigEntity sysConfigEntity = sysConfigService.getDefaultConfig();
        SysConfigVo sysConfigVo = new SysConfigVo();
        BeanUtil.copyProperties(sysConfigEntity, sysConfigVo);
        return R.ok(sysConfigVo);
    }

    @PostMapping(value = "update")
    @Operation(summary = "更新系统配置")
    @SysLog("修改系统配置" )
    public R update(@RequestBody @Validated SysConfigVo sysConfigVo) {
        SysConfigEntity sysConfigEntity = sysConfigService.getDefaultConfig();
        BeanUtil.copyProperties(sysConfigVo, sysConfigEntity);
        sysConfigService.updateById(sysConfigEntity);

        ModifySysInfoDto modifySysInfoDto = new ModifySysInfoDto();
        modifySysInfoDto.setSysName(sysConfigVo.getSysName());
        modifySysInfoDto.setDeclaration(sysConfigVo.getDeclaration());
        SpringUtil.getApplicationContext().publishEvent(modifySysInfoDto);
        return R.ok();
    }

}
